package com.wyix;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class SwingBackgroundProcessingDemo extends JFrame {
    private JTextArea logArea;
    private JButton startButton;
    private JProgressBar progressBar;

    public SwingBackgroundProcessingDemo() {
        setTitle("图片批量处理工具");
        setSize(600, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        initUI();
    }

    private void initUI() {
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 日志区域
        logArea = new JTextArea();
        logArea.setEditable(false);
        JScrollPane logScrollPane = new JScrollPane(logArea);
        mainPanel.add(logScrollPane, BorderLayout.CENTER);

        // 底部控制栏
        JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));

        startButton = new JButton("开始处理");
        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                startButton.setEnabled(false);
                new ImageProcessingWorker().execute(); // 启动后台任务
            }
        });
        bottomPanel.add(startButton);

        progressBar = new JProgressBar(0, 100);
        progressBar.setStringPainted(true);
        bottomPanel.add(progressBar);

        mainPanel.add(bottomPanel, BorderLayout.SOUTH);

        add(mainPanel);
    }

    private void log(String message) {
        logArea.append(message + "\n");
        logArea.setCaretPosition(logArea.getDocument().getLength()); // 自动滚动到最新日志
    }

    // 后台任务类（继承SwingWorker）
    private class ImageProcessingWorker extends SwingWorker<Void, Integer> {
        private static final int TOTAL_FILES = 10; // 模拟10个文件需要处理

        @Override
        protected Void doInBackground() throws Exception {
            log("后台线程启动，开始处理图片...");
            for (int i = 0; i < TOTAL_FILES; i++) {
                // 模拟耗时操作（图片压缩/重命名等）
                Thread.sleep(500); // 模拟处理每个文件耗时500ms
                int progress = (i + 1) * 100 / TOTAL_FILES;
                setProgress(progress); // 更新进度
                publish(progress); // 发送进度到主线程
                log("处理第 " + (i + 1) + " 张图片（模拟）");
            }
            log("所有图片处理完成！");
            return null;
        }

        @Override
        protected void process(List<Integer> chunks) {
            // 主线程更新进度条
            int progress = chunks.get(chunks.size() - 1);
            progressBar.setValue(progress);
            progressBar.setString("处理中：" + progress + "%");
        }

        @Override
        protected void done() {
            startButton.setEnabled(true);
            progressBar.setValue(100);
            progressBar.setString("处理完成！");
            try {
                get(); // 捕获后台任务中的异常
            } catch (InterruptedException | ExecutionException e) {
                log("处理过程中发生错误：" + e.getCause().getMessage());
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        // 确保Swing组件在事件分派线程中创建
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SwingBackgroundProcessingDemo().setVisible(true);
            }
        });
    }
}